/*
 * Software project 13b - EX4
 * Dor porat - dorporat | 026558338
 * Chen salomon - chensalomon | 200713998
 */

#include <stdio.h>
#include <string.h>
#include "Consts.h"
#include "Graph.h"
#include "FileWrapper.h"
#include "cluster_editing.h"
#include "ClusterInfo.h"

int main(int argc, char * argv[])
{
	int status;
	char* inDirectory = NULL;
	char* outDirectory = NULL;
	char* probname = NULL;
	double defaultWeight,score=0,avgInEdge=0,avgBetweenEdge=0;
	graph* gr =NULL;
    clusterInfo* defaultCluster = NULL;
	status=0;
	/* Get command line parameters*/
	if(argc != 4)
	{
		fprintf (stderr, "Error : wrong number of params\n");
		status=-1;
		return status;
	}
    inDirectory = argv[1];
	outDirectory = argv[2];
    if(inDirectory[strlen(inDirectory)-1] != '/' || outDirectory[strlen(outDirectory)-1] != '/')
    {
        fprintf (stderr, "Error : Directory is not in correct format\n");
        status=-1;
        return status;
	}
    /* check if default weight is in the correct format*/
    defaultWeight = parseDouble(argv[3],TRUE);
    if(defaultWeight == -1)
    {
    	fprintf (stderr, "Error: default weight should be double between 0-1\n");
        status=-1;
		return status;
	}
    /* Initialize the graph object*/
	gr = initGraph(defaultWeight);
	if(gr == NULL){
		status=-1;
		goto TERMINATE;
	}
	/* Fill the graph according to the input file*/
	if(fillGraph(gr,inDirectory) == ERROR){
		status=-1;
		goto TERMINATE;
	}

    if(gr -> numofVertices==0)
    {
    	fprintf (stderr, "Error: graph contains no vertices\n");
        return status;
    }
    else if(gr -> numofVertices==1)
    {
    	/* If there is only one vertex in the graph then there is no reason to run CPLEX*/
        defaultCluster = malloc(sizeof(clusterInfo));
        if(defaultCluster == NULL)
        {
            fprintf (stderr, "Error: standard function malloc has failed\n");
            status = -1;
            goto TERMINATE;
        }
        defaultCluster->id = 1;
        defaultCluster->diameter=0;
        defaultCluster->size=1;
        defaultCluster->score=0;
        gr-> vertices[0] -> cluster = defaultCluster;
        addCluster(gr, defaultCluster);
    }
    else
    {
    	/* assign problem name*/
		probname = (char*)malloc(sizeof(char)*(strlen(outDirectory) + strlen(CLUSTER_EDITING_PROBLEM_NAME)+1));
		if (probname == NULL){
			fprintf (stderr, "Error: standard function malloc has failed\n");
			status=-1;
			goto TERMINATE;
		}
		strcpy(probname, outDirectory);
		strcat(probname, CLUSTER_EDITING_PROBLEM_NAME);
    	/* run the cluster editing method*/
        status = cluster(gr, probname,&score,&avgInEdge,&avgBetweenEdge);
    }
    /* write the output files*/
    if(writeResults(gr, outDirectory,avgInEdge,avgBetweenEdge,score) == ERROR ||
       writeXml(gr,outDirectory, BEST_CLUSTERS_FILE) == ERROR ||
       writeXml(gr,outDirectory, SOLUTION_FILE) == ERROR)
        status = -1;
    
TERMINATE:
    free(probname);
    free_graph(gr);
	return status;
}
